12주차 - 얼굴 검출(face detection)¶


▶ 얼굴 검출과 인식¶

  • 얼굴 검출
    • 얼굴의 공통된 특징을 이용하여 얼굴의 위치를 검출
  • 얼굴 인식
    • 얼굴에 포함된 개인의 특징을 이용하여 개인 식별

▶ 얼굴 검출 방법(실습)¶

  • Haar feature-based cascade classifiers
    • Paul Viola와 Michael Jones가 2001년 "Rapid Object Detection using a Boosted Cascade of Simple Features" 논문에서 제안한 객체 감지 방법
    • https://docs.opencv.org/3.4/db/d28/tutorial_cascade_classifier.html

image.png

  • HOG(Histogram of Oriented Gradients)
    • 픽셀값의 변화로 파악할 수 있는 영상 밝기 변화의 방향을 그래디언트(gradient)로 표현하고, 이로부터 객체의 형태를 검출

image-2.png

  • dlib 설치
    • 시작 메뉴 > Anaconda3 (64-bit) > Anaconda Powershell Prompt (Anaconda3) 관리자 권한으로 실행
    • 명령어: conda install -c conda-forge dlib
In [3]:
### Packages
import cv2
import numpy as np
import matplotlib.pyplot as plt
In [4]:
### 출력 영상 크기
plt.rcParams["figure.figsize"] = (16,9)
### 한글 표시
plt.rcParams['font.family'] = "Gulim"   # 'AppleGothic' in mac

■ Haar feature-based cascade classifiers¶

In [5]:
### 영상 읽기
img_file = r'D:\image\bp2.jpg'
img_bgr = cv2.imread(img_file)

### 영상 출력
plt.imshow(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB))
plt.show()
In [6]:
### Package
from distutils.sysconfig import get_python_lib

### 캐스케이드 파일
cascade_file = get_python_lib() + r"\cv2\data\haarcascade_frontalface_alt2.xml"
cascade_file
Out[6]:
'C:\\ProgramData\\Anaconda3\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml'
In [7]:
### 캐스케이드 파일 읽기
cascade = cv2.CascadeClassifier(cascade_file)

### 그레이스케일로 변환
img_gs = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)

### 얼굴 검출
face_list = cascade.detectMultiScale(img_gs, minSize = (30, 30))
In [8]:
### 얼굴 검출 좌표 - [x, y, w, h]
face_list
Out[8]:
array([[214,  74,  71,  71],
       [376,  64,  65,  65],
       [141, 181,  48,  48],
       [ 35,  64,  72,  72]])
In [9]:
### 얼굴 좌표 확인
if len(face_list) > 0:
    
    ### 이미지 복사
    img_out = img_bgr.copy()
    
    ### 색상 - red
    color = (0, 0, 255)
    
    ### 얼굴 영역 표시
    for face in face_list :
        x, y, w, h = face
        cv2.rectangle(img_out, (x, y), (x+w, y+h), color, thickness = 3)
    
    ### RGB로 변환 후 이미지 출력
    plt.imshow(cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB))
    plt.show()
else:
    print("no face")

■ 얼굴 모자이크 처리¶

In [10]:
### 모자이크 처리 함수
def fn_mosaic (img, rect, size = 9) :
    x1, y1, x2, y2 = rect
    w = x2 - x1
    h = y2 - y1
    img_small = cv2.resize(img[y1:y2, x1:x2], (size, size))
    img[y1:y2, x1:x2] = cv2.resize(img_small, (w, h), 
                                   interpolation = cv2.INTER_AREA)
    return img
In [11]:
### 이미지 복사
img_out = img_bgr.copy()

### 모자이크 처리
for x, y, w, h in face_list :
    ### 이미지 삽입
    img_out = fn_mosaic(img_out, (x, y, x+w, y+h))

    ### RGB로 변환 후 이미지 출력
plt.imshow(cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB))
plt.show()

■ HOG(Histogram of Oriented Gradients)¶

In [12]:
### Packages
import cv2
import numpy as np
import matplotlib.pyplot as plt
import dlib
In [13]:
### 얼굴 검출기 - HOG
detector_hog = dlib.get_frontal_face_detector()

### 얼굴 검출 - RGB 영상 사용
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
dlib_rects = detector_hog(img_rgb, 1)
In [14]:
### 얼굴 검출 좌표 - [(x1, y1) (x2, y2)]
dlib_rects
Out[14]:
rectangles[[(218, 80) (280, 142)], [(38, 73) (100, 135)], [(377, 73) (439, 135)], [(501, 66) (563, 129)]]
In [15]:
### 얼굴 좌표 확인
if len(face_list) > 0:
    
    ### 이미지 복사
    img_out = img_bgr.copy()
    
    ### 색상 - green
    color = (0, 255, 0)
    
    ### 얼굴 영역 표시
    for dlib_rect in dlib_rects:
        rect_lt = (dlib_rect.left(), dlib_rect.top())
        rect_rb = (dlib_rect.right(), dlib_rect.bottom())
        cv2.rectangle(img_out, rect_lt, rect_rb, color, 2, 
                      lineType=cv2.LINE_AA)
    
    ### RGB로 변환 후 이미지 출력
    plt.imshow(cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB))
    plt.show()
else:
    print("no face")

■ 얼굴 모자이크 처리¶

In [16]:
### 이미지 복사
img_out = img_bgr.copy()

### 모자이크 처리
for dlib_rect in dlib_rects:
    ### 이미지 삽입
    x1 = dlib_rect.left()
    y1 = dlib_rect.top()
    x2 = dlib_rect.right()
    y2 = dlib_rect.bottom()
    img_out = fn_mosaic(img_out, (x1, y1, x2, y2))

### RGB로 변환 후 이미지 출력
plt.imshow(cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB))
plt.show()

■ 얼굴 모자이크 처리 - 웹캠(webcam)¶

In [17]:
### 검출기
detector_hog = dlib.get_frontal_face_detector()

### 카메라 연결
cap = cv2.VideoCapture(0)

### 동영상 출력
while cv2.waitKey(1) < 0:
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret:
        ### 얼굴 검출
        dlib_rects = detector_hog(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), 1)

        ### 모자이크 처리
        for dlib_rect in dlib_rects:
            ### 이미지 삽입
            x1 = dlib_rect.left()
            y1 = dlib_rect.top()
            x2 = dlib_rect.right()
            y2 = dlib_rect.bottom()
            frame = fn_mosaic(frame, (x1, y1, x2, y2))
        
        ### Frame 출력
        cv2.imshow("VideoFrame", frame)
    else:
        print("Can't receive frame. Exiting...")
        break

### When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

▶ Dlib landmark localization¶

  • 얼굴에서 68개 이목구비 위치 검출
    • ibug 300-W 데이터셋으로 학습한 pretrained model을 제공
    • regression tree의 앙상블 모델을 사용
      • 학습된 모형 다운로드: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
    • 얼굴 검출, 이목구비의 위치 및 움직임, 얼굴 인식에 활용
  • 68개 이목구비 위치 image.png
  • Landmark dataset image-2.png

■ Face landmarks¶

In [18]:
### 영상 읽기
img_file = r'D:\image\bp2.jpg'
img_bgr = cv2.imread(img_file)

### 얼굴 검출기 - HOG
detector_hog = dlib.get_frontal_face_detector()

### 얼굴 검출 - RGB 영상 사용
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
dlib_rects = detector_hog(img_rgb, 1)
In [20]:
### 검출기
landmark_predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

### face landmark
list_landmarks = []

### face landmark 검출
for dlib_rect in dlib_rects:
    points = landmark_predictor(img_rgb, dlib_rect)
    ### face landmark 좌표 저장
    list_points = list(map(lambda p: (p.x, p.y), points.parts()))
    list_landmarks.append(list_points)
In [26]:
### face landmark 확인
len(list_landmarks), list_landmarks[0][:6]
Out[26]:
(4, [(217, 99), (218, 107), (220, 114), (221, 122), (225, 129), (230, 135)])
In [27]:
### 이미지 복사
img_out = img_bgr.copy()

### face landmark 표시
for landmark in list_landmarks:
    for point in landmark:
        cv2.circle(img_out, point, 2, (255, 255, 255), -1)

### 영상 출력
plt.imshow(cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB))
plt.show()

■ Landmarks - 웹캠(webcam)¶

In [28]:
### 검출기
detector_hog = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

### 카메라 연결
cap = cv2.VideoCapture(0)

### 동영상 출력
while cv2.waitKey(1) < 0:
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret:
        ### 얼굴 검출
        dlib_rects = detector_hog(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), 1)
        
        ### face landmark
        list_landmarks = []
        
        ### face landmark 검출
        for dlib_rect in dlib_rects:
            points = landmark_predictor(frame, dlib_rect)
            ### face landmark 좌표 저장
            list_points = list(map(lambda p: (p.x, p.y), points.parts()))
            list_landmarks.append(list_points)

        ### face landmark 표시
        for landmark in list_landmarks:
            for point in landmark:
                cv2.circle(frame, point, 2, (255, 255, 255), -1)
        
        ### Frame 출력
        cv2.imshow("VideoFrame", frame)
    else:
        print("Can't receive frame. Exiting...")
        break

### When everything done, release the capture
cap.release()
cv2.destroyAllWindows()